<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>发放失败记录管理</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="../css/common.css">
</head>
<body>
<div class="container">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>优惠券发放失败记录</h2>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
        <div class="row g-3">
            <div class="col-md-4">
                <input type="number" id="searchBatchId" class="form-control" placeholder="输入批次ID搜索">
            </div>
            <div class="col-md-4">
                <input type="number" id="searchUserId" class="form-control" placeholder="输入用户ID搜索">
            </div>
            <div class="col-md-4">
                <button class="btn btn-success w-100" onclick="queryFailList(1)">搜索</button>
                <button class="btn btn-light w-100 mt-2" onclick="resetSearch()">重置</button>
            </div>
        </div>
    </div>

    <!-- 失败记录列表 -->
    <div class="card">
        <div class="card-body">
            <table class="table table-hover table-bordered">
                <thead class="table-primary">
                <tr>
                    <th>记录ID</th>
                    <th>批次ID（任务ID）</th>
                    <th>用户ID</th>
                    <th>用户名</th>
                    <th>优惠券模板</th>
                    <th>失败原因</th>
                    <th>记录时间</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody id="failTableBody">
                <tr><td colspan="8" class="text-center">加载中...</td></tr>
                </tbody>
            </table>
        </div>
    </div>

    <!-- 分页 -->
    <div id="pagination-container"></div>
</div>

<!-- 查看失败详情弹窗 -->
<div class="modal fade" id="failDetailModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">失败记录详情</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="row g-3">
                    <div class="col-md-6">
                        <label class="form-label fw-bold">记录ID：</label>
                        <span id="detailId"></span>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label fw-bold">批次ID（任务ID）：</label>
                        <span id="detailBatchId"></span>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label fw-bold">用户ID：</label>
                        <span id="detailUserId"></span>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label fw-bold">用户名：</label>
                        <span id="detailUsername"></span>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label fw-bold">优惠券模板：</label>
                        <span id="detailTemplateName"></span>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label fw-bold">记录时间：</label>
                        <span id="detailCreateTime"></span>
                    </div>
                    <div class="col-md-12">
                        <label class="form-label fw-bold">失败原因：</label>
                        <p id="detailReason" class="text-danger"></p>
                    </div>
                    <div class="col-md-12">
                        <label class="form-label fw-bold">扩展信息：</label>
                        <pre id="detailExtInfo" class="bg-light p-3 rounded"></pre>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="../js/common.js"></script>
<script>
    let currentPage = 1;
    const pageSize = 10;

    window.onload = function () {
        queryFailList(currentPage);
    };

    // 查询失败记录列表
    async function queryFailList(pageNum) {
        try {
            const batchId = document.getElementById("searchBatchId").value;
            const userId = document.getElementById("searchUserId").value;

            const res = await axios.get("/api/coupon-task-fails/page", {
                params: {
                    pageNum,
                    pageSize,
                    batchId: batchId || undefined,
                    userId: userId || undefined
                }
            });

            const { records, total } = res.data;
            currentPage = pageNum;
            const tableBody = document.getElementById("failTableBody");
            tableBody.innerHTML = "";

            if (records.length === 0) {
                tableBody.innerHTML = '<tr><td colspan="8" class="text-center">暂无失败记录</td></tr>';
                return;
            }

            records.forEach(fail => {
                const row = `
                        <tr>
                            <td>${fail.id}</td>
                            <td>${fail.batchId}</td>
                            <td>${fail.userId}</td>
                            <td>${fail.user?.username || "未知用户"}</td>
                            <td>${fail.couponTemplate?.name || "未知模板"}</td>
                            <td class="text-danger">${fail.failReason}</td>
                            <td>${Common.formatDate(fail.createTime)}</td>
                            <td>
                                <button class="btn btn-sm btn-outline-primary" onclick="viewFailDetail(${fail.id})">查看详情</button>
                            </td>
                        </tr>
                    `;
                tableBody.innerHTML += row;
            });

            Common.renderPagination(total, pageNum, pageSize, queryFailList);
        } catch (err) {
            Common.errorMsg("查询失败记录失败：" + err.message);
            document.getElementById("failTableBody").innerHTML = '<tr><td colspan="8" class="text-center">查询失败</td></tr>';
        }
    }

    // 重置搜索
    function resetSearch() {
        document.getElementById("searchBatchId").value = "";
        document.getElementById("searchUserId").value = "";
        queryFailList(1);
    }

    // 查看失败详情
    async function viewFailDetail(failId) {
        try {
            const res = await axios.get(`/api/coupon-task-fails/${failId}`);
            const fail = res.data;

            // 填充详情
            document.getElementById("detailId").textContent = fail.id;
            document.getElementById("detailBatchId").textContent = fail.batchId;
            document.getElementById("detailUserId").textContent = fail.userId;
            document.getElementById("detailUsername").textContent = fail.user?.username || "未知用户";
            document.getElementById("detailTemplateName").textContent = fail.couponTemplate?.name || "未知模板";
            document.getElementById("detailCreateTime").textContent = Common.formatDate(fail.createTime);
            document.getElementById("detailReason").textContent = fail.failReason;

            // 格式化扩展信息
            const extInfo = fail.extInfo ? JSON.stringify(JSON.parse(fail.extInfo), null, 2) : "无";
            document.getElementById("detailExtInfo").textContent = extInfo;

            new bootstrap.Modal(document.getElementById("failDetailModal")).show();
        } catch (err) {
            Common.errorMsg("加载失败详情失败：" + err.message);
        }
    }
</script>
</body>
</html>